// 用于控制翻译是否应该停止
let shouldStopTranslation = false;
let currentController = null;

// 在全局作用域添加变量跟踪翻译状态
let isTranslating = false;

// 监听来自popup和background的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'translate' && request.apiKey) {
    // 重置停止标志和控制器
    shouldStopTranslation = false;
    currentController = new AbortController();
    
    // 开始翻译
    translatePage(request.apiKey, currentController.signal, request.showOriginal).then(() => {
      sendResponse({status: 'success'});
    }).catch(error => {
      sendResponse({status: 'error', message: error.message});
    });
    return true; // 保持消息通道开放
  } else if (request.action === 'stopTranslate') {
    shouldStopTranslation = true;
    if (currentController) {
      currentController.abort(); // 取消所有进行中的fetch请求
    }
    sendResponse({status: 'success', message: '翻译已停止'});
    return false;
  } else if (request.action === 'translateSelection') {
    handleSelectionTranslation(request.text, request.apiKey, request.showOriginal);
    return false;
  } else if (request.action === 'showMessage') {
    showFloatingMessage(request.message);
    return false;
  } else if (request.action === 'getTranslationStatus') {
    sendResponse({ isTranslating });
    return true;
  }
});

// 显示浮动消息
function showFloatingMessage(message) {
  const messageDiv = document.createElement('div');
  messageDiv.style.position = 'fixed';
  messageDiv.style.top = '10px';
  messageDiv.style.right = '10px';
  messageDiv.style.padding = '10px';
  messageDiv.style.background = '#0078d4';
  messageDiv.style.color = 'white';
  messageDiv.style.borderRadius = '4px';
  messageDiv.style.zIndex = '10000';
  messageDiv.style.maxWidth = '300px';
  messageDiv.textContent = message;
  document.body.appendChild(messageDiv);

  setTimeout(() => {
    messageDiv.remove();
  }, 3000);
}

// 处理选中文本的翻译
async function handleSelectionTranslation(text, apiKey, showOriginal) {
  // 获取选中的范围
  const selection = window.getSelection();
  if (!selection.rangeCount) return;

  const range = selection.getRangeAt(0);

  // 创建临时控制器用于这次翻译
  const controller = new AbortController();

  try {
    // 创建加载提示
    const loadingDiv = document.createElement('div');
    loadingDiv.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 15px 25px;
      background: rgba(0, 120, 212, 0.9);
      color: white;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      z-index: 10001;
      font-size: 14px;
    `;
    loadingDiv.textContent = '正在翻译选中内容...';
    document.body.appendChild(loadingDiv);

    // 调用翻译API
    const translation = await translateText(text, apiKey, controller.signal);

    // 创建半透明背景
    const overlay = document.createElement('div');
    overlay.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      z-index: 10000;
    `;

    // 创建翻译结果弹出框
    const resultDiv = document.createElement('div');
    resultDiv.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 90%;
      max-width: 600px;
      max-height: 80vh;
      overflow-y: auto;
      padding: 20px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
      z-index: 10001;
      font-size: 14px;
      line-height: 1.6;
    `;

    // 添加关闭按钮
    const closeButton = document.createElement('button');
    closeButton.textContent = '×';
    closeButton.style.cssText = `
      position: absolute;
      right: 12px;
      top: 12px;
      width: 24px;
      height: 24px;
      border: none;
      background: none;
      font-size: 24px;
      cursor: pointer;
      color: #666;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      transition: background-color 0.2s;
      padding: 0;
      line-height: 1;
    `;
    closeButton.addEventListener('mouseover', () => {
      closeButton.style.backgroundColor = '#f0f0f0';
    });
    closeButton.addEventListener('mouseout', () => {
      closeButton.style.backgroundColor = 'transparent';
    });
    closeButton.addEventListener('click', () => {
      overlay.remove();
      resultDiv.remove();
    });

    // 添加内容容器
    const contentDiv = document.createElement('div');
    contentDiv.style.marginRight = '20px';

    // 如果启用了显示原文
    if (showOriginal) {
      const originalDiv = document.createElement('div');
      originalDiv.style.cssText = `
        margin-bottom: 12px;
        padding-bottom: 12px;
        border-bottom: 1px solid #eee;
        color: #666;
        font-size: 14px;
        white-space: pre-wrap;
        word-wrap: break-word;
      `;
      originalDiv.textContent = text;
      contentDiv.appendChild(originalDiv);
    }

    // 添加翻译结果
    const translatedDiv = document.createElement('div');
    translatedDiv.style.cssText = `
      color: #333;
      font-size: 16px;
      white-space: pre-wrap;
      word-wrap: break-word;
    `;
    translatedDiv.textContent = translation;
    contentDiv.appendChild(translatedDiv);

    // 组装弹出框
    resultDiv.appendChild(closeButton);
    resultDiv.appendChild(contentDiv);

    // 添加到页面
    document.body.appendChild(overlay);
    document.body.appendChild(resultDiv);
    loadingDiv.remove();

    // 点击半透明背景关闭弹出框
    overlay.addEventListener('click', () => {
      overlay.remove();
      resultDiv.remove();
    });

    // 阻止点击弹出框本身时关闭
    resultDiv.addEventListener('click', (event) => {
      event.stopPropagation();
    });

    // ESC键关闭弹出框
    const handleEsc = (event) => {
      if (event.key === 'Escape') {
        overlay.remove();
        resultDiv.remove();
        document.removeEventListener('keydown', handleEsc);
      }
    };
    document.addEventListener('keydown', handleEsc);

  } catch (error) {
    showFloatingMessage(`翻译出错: ${error.message}`);
  }
}

// 检查节点是否在不应翻译的区域内
function isInExcludedArea(node) {
  let parent = node.parentElement;
  
  // 检查父元素
  while (parent) {
    // 检查标签名
    if (['HEADER', 'FOOTER', 'NAV'].includes(parent.tagName)) {
      return true;
    }
    
    // 检查常见的header、footer和目录类名和ID
    const classAndId = (parent.className || '') + ' ' + (parent.id || '');
    const excludedPatterns = [
      /header/i,
      /footer/i,
      /^top-nav/i,
      /^bottom-nav/i,
      /^site-header/i,
      /^site-footer/i,
      /^main-header/i,
      /^main-footer/i,
      /^page-header/i,
      /^page-footer/i,
      /^nav-header/i,
      /^nav-footer/i,
      // 目录相关
      /toc/i,                    // Table of Contents
      /navigation/i,
      /nav-/i,
      /sidebar/i,
      /index/i,
      /directory/i,
      /category/i,
      /chapters?/i,             // chapter或chapters
      /outline/i,
      /^nav$/i,
      /breadcrumb/i,            // 面包屑导航
      /pagination/i,            // 分页
      /tabs?/i,                 // tab或tabs
      /menu-item/i,
      /dropdown/i,
      /submenu/i,
      /navbar/i,
      /sitemap/i,
      /tree-nav/i,
      /side-nav/i,
      /main-nav/i,
      /primary-nav/i,
      /secondary-nav/i
    ];
    
    if (excludedPatterns.some(pattern => pattern.test(classAndId)) && !['HTML', 'BODY'].includes(parent.tagName)) {
      return true;
    }
    // 检查HTML5语义化标签
    if (['nav', 'aside', 'menu'].includes(parent.tagName.toLowerCase())) {
      return true;
    }

    // 检查ARIA角色
    const role = parent.getAttribute('role');
    if (role && ['navigation', 'menu', 'menubar', 'tree', 'directory', 'complementary'].includes(role)) {
      return true;
    }
    
    parent = parent.parentElement;
  }
  
  return false;
}

// 检查节点是否在代码块内
function isInCodeBlock(node) {
  const codeElements = ['PRE', 'CODE', 'SCRIPT', 'STYLE'];
  let parent = node.parentElement;
  
  // 检查父元素
  while (parent) {
    if (codeElements.includes(parent.tagName) ||
        parent.classList.contains('code') ||
        parent.classList.contains('highlight') ||
        parent.classList.contains('prettyprint') ||
        parent.getAttribute('class')?.includes('language-') ||
        parent.getAttribute('class')?.includes('syntax-') ||
        parent.getAttribute('class')?.includes('hljs-')) {
      return true;
    }
    parent = parent.parentElement;
  }
  
  return false;
}

// 检查文本是否看起来像代码
function looksLikeCode(text) {
  // 检查常见的代码特征
  const codePatterns = [
    /^import\s+[\w\s,{}*]+\s+from\s+['"][^'"]+['"];?$/,  // import 语句
    /^(const|let|var)\s+\w+\s*=\s*/,                     // 变量声明
    /^function\s+\w+\s*\([^)]*\)\s*{/,                   // 函数声明
    /^class\s+\w+(\s+extends\s+\w+)?\s*{/,               // 类声明
    /[{}\[\]()];$/,                                       // 以括号或分号结尾
    /^\s*if\s*\([^)]*\)\s*{/,                            // if 语句
    /^\s*for\s*\([^)]*\)\s*{/,                           // for 循环
    /^\s*while\s*\([^)]*\)\s*{/,                         // while 循环
    /^\s*return\s+.*/,                                    // return 语句
    /[<>!=]==?/,                                          // 比较运算符
    /&&|\|\|/,                                            // 逻辑运算符
    /\${.*}/,                                             // 模板字符串插值
    /^[a-zA-Z_$][a-zA-Z0-9_$]*\([^)]*\)/,               // 函数调用
    /^@\w+/,                                              // 装饰器
    /^#\w+/,                                              // 私有字段
    /=>/,                                                 // 箭头函数
    /\$\w+/,                                              // jQuery选择器或PHP变量
    /^<!DOCTYPE|^<html|^<\?php/i,                         // HTML或PHP开头
  ];

  return codePatterns.some(pattern => pattern.test(text.trim()));
}

// 延迟函数
const delay = ms => new Promise((resolve, reject) => {
  const timeout = setTimeout(resolve, ms);
  if (shouldStopTranslation) {
    clearTimeout(timeout);
    reject(new Error('翻译已取消'));
  }
});

// 翻译单个文本
async function translateText(text, apiKey, signal) {
  if (shouldStopTranslation) {
    throw new Error('翻译已取消');
  }

  const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    },
    body: JSON.stringify({
      model: "deepseek-chat",
      messages: [
        {
          role: "system",
          content: "You are a translator. Translate the following English text to Chinese. Only return the translated text, no explanations."
        },
        {
          role: "user",
          content: text
        }
      ]
    }),
    signal // 添加signal以支持取消请求
  });

  if (!response.ok) {
    throw new Error(`API请求失败: ${response.status}`);
  }

  const data = await response.json();
  return data.choices[0].message.content;
}

// 创建双语文本节点
function createBilingualNode(originalText, translatedText) {
  const container = document.createElement('span');
  container.style.display = 'inline-block';
  
  const originalSpan = document.createElement('span');
  originalSpan.textContent = originalText;
  originalSpan.style.color = '#666';
  originalSpan.style.marginRight = '4px';
  
  const translatedSpan = document.createElement('span');
  translatedSpan.textContent = translatedText;
  
  container.appendChild(originalSpan);
  container.appendChild(translatedSpan);
  
  return container;
}

// 检查节点是否在段落或列表内
function isInParagraphOrList(node) {
  let parent = node.parentElement;
  while (parent) {
    if (parent.tagName === 'P' || parent.tagName === 'LI') {
      return true;
    }
    parent = parent.parentElement;
  }
  return false;
}

// 获取段落或列表项的完整文本
function getBlockText(node) {
  let parent = node.parentElement;
  while (parent && parent.tagName !== 'P' && parent.tagName !== 'LI') {
    parent = parent.parentElement;
  }
  
  if (!parent) return null;
  
  // 获取段落或列表项内所有文本节点
  const textNodes = document.evaluate(
    './/text()[normalize-space(.)!=""]',
    parent,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );
  
  let fullText = '';
  let processedNodes = new Set();
  
  for (let i = 0; i < textNodes.snapshotLength; i++) {
    const textNode = textNodes.snapshotItem(i);
    processedNodes.add(textNode);
    fullText += (i > 0 ? ' ' : '') + textNode.textContent.trim();
  }
  
  return { text: fullText, nodes: processedNodes };
}

// 翻译函数
async function translatePage(apiKey, signal, showOriginal) {
  isTranslating = true;

  // 创建加载提示
  const loadingDiv = document.createElement('div');
  loadingDiv.style.position = 'fixed';
  loadingDiv.style.top = '10px';
  loadingDiv.style.right = '10px';
  loadingDiv.style.padding = '10px';
  loadingDiv.style.background = '#0078d4';
  loadingDiv.style.color = 'white';
  loadingDiv.style.borderRadius = '4px';
  loadingDiv.style.zIndex = '10000';
  loadingDiv.textContent = '翻译中...';
  document.body.appendChild(loadingDiv);

  try {
    // 获取页面文本内容
    const textNodes = document.evaluate(
      '//text()[normalize-space(.)!=""]',
      document.body,
      null,
      XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
      null
    );

    let translatedCount = 0;
    let totalValidNodes = 0;


    // 首先计算需要翻译的节点数量
    for (let i = 0; i < textNodes.snapshotLength; i++) {
      if (shouldStopTranslation) {
        throw new Error('翻译已取消');
      }

      const node = textNodes.snapshotItem(i);
      const text = node.textContent.trim();
      
      if (text && /[a-zA-Z]/.test(text) && 
          !isInCodeBlock(node) && 
          !looksLikeCode(text) &&
          !isInExcludedArea(node)) {
        totalValidNodes++;
      }
    }

    const processedNodes = new Set();

    // 遍历文本节点进行翻译
    for (let i = 0; i < textNodes.snapshotLength; i++) {
      if (shouldStopTranslation) {
        throw new Error('翻译已取消');
      }

      const node = textNodes.snapshotItem(i);
      
      // 如果节点已经处理过，跳过
      if (processedNodes.has(node)) continue;
      
      const text = node.textContent.trim();
      
      // 跳过空文本、非英文内容
      if (!text || !/[a-zA-Z]/.test(text)) continue;

      // 如果在段落或列表内，获取整个块的文本
      if (isInParagraphOrList(node)) {
        if (isInExcludedArea(node)) continue;
        
        const blockInfo = getBlockText(node);
        if (blockInfo) {
          // 将块内所有节点标记为已处理
          blockInfo.nodes.forEach(n => processedNodes.add(n));
          
          try {
            const translation = await translateText(blockInfo.text, apiKey, signal);
            
            if (showOriginal) {
              // 创建双语对照节点
              const bilingualNode = createBilingualNode(blockInfo.text, translation);
              // 替换第一个节点，删除其他节点
              node.parentNode.replaceChild(bilingualNode, node);
              blockInfo.nodes.forEach(n => {
                if (n !== node && n.parentNode) {
                  n.parentNode.removeChild(n);
                }
              });
            } else {
              // 仅在第一个节点显示译文，删除其他节点
              node.textContent = translation;
              blockInfo.nodes.forEach(n => {
                if (n !== node && n.parentNode) {
                  n.parentNode.removeChild(n);
                }
              });
            }
            
            translatedCount++;
          } catch (error) {
            if (error.name === 'AbortError' || error.message === '翻译已取消') {
              throw new Error('翻译已取消');
            }
            console.error('翻译错误:', error);
            continue;
          }
        }
      } else {
        // 不在段落内时，保持原有的跳过逻辑
        if (isInCodeBlock(node) || looksLikeCode(text) || isInExcludedArea(node)) continue;
        try {
          const translation = await translateText(text, apiKey, signal);
          if (showOriginal) {
            const bilingualNode = createBilingualNode(text, translation);
            node.parentNode.replaceChild(bilingualNode, node);
          } else {
            node.textContent = translation;
          }
          translatedCount++;
        } catch (error) {
          if (error.name === 'AbortError' || error.message === '翻译已取消') {
            throw new Error('翻译已取消');
          }
          console.error('翻译错误:', error);
          continue;
        }
      }
      
      await delay(100);
    }
    
    if (!shouldStopTranslation) {
      loadingDiv.textContent = '翻译完成';
    }
  } catch (error) {
    if (error.message === '翻译已取消') {
      loadingDiv.textContent = '翻译已停止';
    } else {
      loadingDiv.textContent = `翻译出错: ${error.message}`;
      console.error('翻译错误:', error);
    }
  } finally {
    if (shouldStopTranslation) {
      isTranslating = false;
    }
  }

  // 3秒后移除提示
  setTimeout(() => {
    loadingDiv.remove();
  }, 3000);
} 